﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Excell_On_Services.Models;
using Excell_On_Services.ViewModels;

namespace Excell_On_Services.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {
        public IEOSRepository Repository { get; set; }

        public AccountController()
            : this(new EFEOSRepository())
        {

        }

        public AccountController(IEOSRepository repository)
        {
            Repository = repository;
        }

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // Danh cho Admin
        // **************************************
        
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        if(User.IsInRole("Client"))
                            return RedirectToAction("Index", "Home");
                        else
                            return RedirectToAction("Index", "Admin");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOnClient()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOnClient(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        if (User.IsInRole("Client"))
                            return RedirectToAction("Index", "Home");
                        else
                            RedirectToAction("Index", "Admin");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************
        [Authorize]
        public ActionResult LogOff()
        {
            bool isClient = false;
            if (User.IsInRole("Client"))
            {
                isClient = true;
            }
            else
            {
                isClient = false;
            }
            FormsService.SignOut();
            Session.Abandon();
            if (isClient)
                return RedirectToAction("Index", "Home");
            else
                return RedirectToAction("Index", "Admin");
        }

        // **************************************
        // URL: /Account/Register
        //      Đây là chỗ để client đăng ký tài khoản
        // **************************************
        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    Roles.AddUserToRole(model.UserName, "Client");
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/UpdateAccount
        // **************************************
        [Authorize(Roles = "Client")]
        public ActionResult UpdateAccount()
        {
            
            string username = User.Identity.Name;
            MembershipUser currentUser = Membership.Provider.GetUser(username, true /* userIsOnline 
*/);
            
            Guid clientID = Repository.GetIdByUsername(username);
            var model = new ClientModel
            {
                Username = username,
                Email = currentUser.Email,
            };

            var client = Repository.FindClientByUsername(username);
            if (client != null)
            {
                model.CompanyName = client.CompanyName;
                model.Description = client.Description;
                model.ProductDescription = client.Product_Description;
                model.Phone = client.Phone;
                model.Address = client.Address;
            }
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Client")]
        public ActionResult UpdateAccount(ClientModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(model);
                string username = User.Identity.Name;
                MembershipUser currentUser = Membership.Provider.GetUser(username, true /* userIsOnline 
*/);
                currentUser.Email = model.Email;
                var client = Repository.FindClientByUsername(username);
                if (client != null)
                {
                    client.CompanyName = model.CompanyName;
                    client.Description = model.Description;
                    client.Product_Description = model.ProductDescription;
                    client.Phone = model.Phone;
                    client.Address = model.Address;
                }
                else
                {
                    client = new Client();
                    client.ClientID = Repository.GetIdByUsername(username);
                    client.CompanyName = model.CompanyName;
                    client.Description = model.Description;
                    client.Product_Description = model.ProductDescription;
                    client.Phone = model.Phone;
                    client.Address = model.Address;
                    Repository.AddClient(client);
                }
                Membership.UpdateUser(currentUser);
                Repository.CommitChanges();
                return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                return View();
            }
            
        }


        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

    }
}
